# 配置统一性验证和修复脚本
# PowerShell Script for Storage Configuration Validation and Repair

Write-Host "=== 存储配置统一性管理工具 ===" -ForegroundColor Green
Write-Host ""

# 检查项目是否存在
$projectPath = "d:\2025\JGSY.PP\Project\JGSY.CMS.LowCode.Platform"
if (-not (Test-Path $projectPath)) {
    Write-Host "错误: 项目路径不存在: $projectPath" -ForegroundColor Red
    exit 1
}

Set-Location $projectPath

# 检查配置文件是否存在
$configFiles = @(
    "appsettings.json",
    "appsettings.Development.json", 
    "appsettings.Production.json"
)

Write-Host "1. 检查配置文件..." -ForegroundColor Yellow
foreach ($file in $configFiles) {
    if (Test-Path $file) {
        Write-Host "✓ $file 存在" -ForegroundColor Green
    } else {
        Write-Host "✗ $file 不存在" -ForegroundColor Red
    }
}

Write-Host ""
Write-Host "2. 编译和运行项目..." -ForegroundColor Yellow

# 编译项目
Write-Host "正在编译项目..." -ForegroundColor Cyan
$buildResult = dotnet build --configuration Release --verbosity quiet
if ($LASTEXITCODE -ne 0) {
    Write-Host "编译失败，请检查项目代码" -ForegroundColor Red
    exit 1
}
Write-Host "✓ 项目编译成功" -ForegroundColor Green

Write-Host ""
Write-Host "3. 配置分析..." -ForegroundColor Yellow

# 创建配置分析脚本
$analysisScript = @"
using System;
using System.IO;
using System.Text.Json;
using Microsoft.Extensions.Configuration;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            // 构建配置
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false)
                .AddJsonFile("appsettings.Development.json", optional: true);
            
            var configuration = builder.Build();
            
            Console.WriteLine("=== 配置分析结果 ===");
            
            // 分析 Upload 配置
            var uploadSection = configuration.GetSection("Upload");
            if (uploadSection.Exists())
            {
                Console.WriteLine("\n[Upload 配置]");
                Console.WriteLine($"StorageType: {uploadSection["StorageType"]}");
                Console.WriteLine($"MaxFileSize: {uploadSection["MaxFileSize"]}");
                Console.WriteLine($"Local.RootPath: {uploadSection["Local:RootPath"]}");
                Console.WriteLine($"Local.BaseUrl: {uploadSection["Local:BaseUrl"]}");
                Console.WriteLine($"CreateDateFolders: {uploadSection["CreateDateFolders"]}");
                Console.WriteLine($"GenerateThumbnails: {uploadSection["GenerateThumbnails"]}");
            }
            else
            {
                Console.WriteLine("\n[Upload 配置] - 不存在");
            }
            
            // 分析 CloudStorage 配置
            var cloudSection = configuration.GetSection("CloudStorage");
            if (cloudSection.Exists())
            {
                Console.WriteLine("\n[CloudStorage 配置]");
                Console.WriteLine($"StorageType: {cloudSection["StorageType"]}");
                Console.WriteLine($"MaxFileSize: {cloudSection["MaxFileSize"]}");
                Console.WriteLine($"Local.RootPath: {cloudSection["Local:RootPath"]}");
                Console.WriteLine($"Local.BaseUrl: {cloudSection["Local:BaseUrl"]}");
                Console.WriteLine($"Local.Enabled: {cloudSection["Local:Enabled"]}");
                Console.WriteLine($"Local.CreateDateFolders: {cloudSection["Local:CreateDateFolders"]}");
                Console.WriteLine($"Local.GenerateThumbnails: {cloudSection["Local:GenerateThumbnails"]}");
            }
            else
            {
                Console.WriteLine("\n[CloudStorage 配置] - 不存在");
            }
            
            // 检查一致性
            Console.WriteLine("\n=== 一致性检查 ===");
            
            if (uploadSection.Exists() && cloudSection.Exists())
            {
                var uploadPath = uploadSection["Local:RootPath"];
                var cloudPath = cloudSection["Local:RootPath"];
                
                if (uploadPath == cloudPath)
                {
                    Console.WriteLine("✓ 路径一致性: 通过");
                }
                else
                {
                    Console.WriteLine($"✗ 路径一致性: 失败 (Upload: {uploadPath}, Cloud: {cloudPath})");
                }
                
                var uploadBaseUrl = uploadSection["Local:BaseUrl"];
                var cloudBaseUrl = cloudSection["Local:BaseUrl"];
                
                if (uploadBaseUrl == cloudBaseUrl)
                {
                    Console.WriteLine("✓ BaseUrl一致性: 通过");
                }
                else
                {
                    Console.WriteLine($"✗ BaseUrl一致性: 失败 (Upload: {uploadBaseUrl}, Cloud: {cloudBaseUrl})");
                }
                
                var uploadMaxSize = uploadSection["MaxFileSize"];
                var cloudMaxSize = cloudSection["MaxFileSize"];
                
                if (uploadMaxSize == cloudMaxSize)
                {
                    Console.WriteLine("✓ 文件大小限制一致性: 通过");
                }
                else
                {
                    Console.WriteLine($"✗ 文件大小限制一致性: 失败 (Upload: {uploadMaxSize}, Cloud: {cloudMaxSize})");
                }
            }
            else
            {
                Console.WriteLine("⚠ 无法进行一致性检查: 缺少 Upload 或 CloudStorage 配置");
            }
            
            Console.WriteLine("\n=== 分析完成 ===");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"配置分析失败: {ex.Message}");
            Environment.Exit(1);
        }
    }
}
"@

# 创建临时分析程序
$tempDir = "temp_config_analysis"
if (Test-Path $tempDir) {
    Remove-Item $tempDir -Recurse -Force
}
New-Item -ItemType Directory -Path $tempDir | Out-Null

$tempProjContent = @"
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
  </ItemGroup>
</Project>
"@

$analysisScript | Out-File -FilePath "$tempDir\Program.cs" -Encoding UTF8
$tempProjContent | Out-File -FilePath "$tempDir\ConfigAnalysis.csproj" -Encoding UTF8

# 复制配置文件到临时目录
foreach ($file in $configFiles) {
    if (Test-Path $file) {
        Copy-Item $file "$tempDir\" -Force
    }
}

# 运行配置分析
Push-Location $tempDir
try {
    Write-Host "正在分析配置..." -ForegroundColor Cyan
    dotnet run --verbosity quiet 2>$null
    if ($LASTEXITCODE -ne 0) {
        Write-Host "配置分析失败" -ForegroundColor Red
    }
} finally {
    Pop-Location
    Remove-Item $tempDir -Recurse -Force -ErrorAction SilentlyContinue
}

Write-Host ""
Write-Host "4. 建议操作..." -ForegroundColor Yellow
Write-Host "如果发现配置不一致，建议执行以下操作:" -ForegroundColor Cyan
Write-Host "• 启动应用程序" -ForegroundColor White
Write-Host "• 访问 /api/StorageConfiguration/validate 检查配置一致性" -ForegroundColor White
Write-Host "• 访问 /api/StorageConfiguration/auto-fix 自动修复配置" -ForegroundColor White
Write-Host "• 访问 /api/StorageConfiguration/fix-all-environments 修复所有环境" -ForegroundColor White

Write-Host ""
Write-Host "5. API 端点说明..." -ForegroundColor Yellow
Write-Host "GET  /api/StorageConfiguration/validate              - 验证配置一致性" -ForegroundColor White
Write-Host "GET  /api/StorageConfiguration/unified               - 获取统一配置" -ForegroundColor White
Write-Host "GET  /api/StorageConfiguration/raw                   - 获取原始配置" -ForegroundColor White
Write-Host "GET  /api/StorageConfiguration/recommendations       - 获取修复建议" -ForegroundColor White
Write-Host "POST /api/StorageConfiguration/auto-fix              - 自动修复当前环境" -ForegroundColor White
Write-Host "POST /api/StorageConfiguration/fix-all-environments  - 修复所有环境" -ForegroundColor White

Write-Host ""
Write-Host "=== 配置统一性检查完成 ===" -ForegroundColor Green

# 询问是否启动应用
$startApp = Read-Host "是否启动应用程序进行测试? (Y/N)"
if ($startApp -eq "Y" -or $startApp -eq "y") {
    Write-Host "正在启动应用程序..." -ForegroundColor Cyan
    Write-Host "应用启动后，可以访问 https://localhost:7001/swagger 查看 API 文档" -ForegroundColor Yellow
    Write-Host "按 Ctrl+C 停止应用程序" -ForegroundColor Yellow
    Write-Host ""
    
    # 启动应用
    dotnet run --configuration Release
}
